package cn.hzc.fortess.core.common;

import com.alibaba.fastjson.JSON;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class GlobalErrorView implements View {

    @Override
    public String getContentType() {
        return "text/html";
    }

    @Override
    public void render(Map<String, ?> map, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json");

        if (map != null && map.get("code") != null && map.get("message") != null) {
            sendToClient(httpServletResponse, (Integer) map.get("code"), map.get("message").toString());
        } else if (map != null && map.get("status") != null && map.get("error") != null) {
            sendToClient(httpServletResponse, Integer.parseInt(map.get("status").toString()), map.get("error").toString());
        } else {
            sendToClient(httpServletResponse, 404, "请求页面不存在");
        }

    }

    private void sendToClient(HttpServletResponse response, Integer code, String message) throws Exception {
        String data = JSON.toJSONString(ResponseData.error(code, message));
        response.getWriter().write(data);
    }
}

